package com.weijun.keepalivedemo

import android.annotation.TargetApi
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.BitmapFactory
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.weijun.keepalive_daemon.DaemonKeepAlive
import com.weijun.keepalive_daemon.callback.DaemonNotifyConfiguration
import com.weijun.keepalive_daemon.isMainProcess
import com.weijun.keepalivedemo.daemon.SystemBroadcastReceiver

/**
 * @author: weijun
 * date: 2023/7/5
 * description:
 */
class App : Application() {

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        DaemonKeepAlive.init(this)
        DaemonKeepAlive.daemonNotifyConfiguration = object : DaemonNotifyConfiguration{
            override fun getIntentNotificationBuilder(context: Context): NotificationCompat.Builder {
                return if (Build.VERSION.SDK_INT >= 26) {
                    NotificationCompat.Builder(context, getIntentChannelId(context))
                } else {
                    NotificationCompat.Builder(context)
                }.apply {
                    setContentTitle("手机优化中")
                    setContentText("正在优化您的手机")
                    setSmallIcon(R.drawable.logo)
                    setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.logo))
                    setAutoCancel(true)
                    setDefaults(4)
                    priority = -1
                }
            }
            @TargetApi(26)
            fun getIntentChannelId(context: Context): String {
                val notificationChannel = NotificationChannel(
                    "com.daemon.lockscreen.brandnew",
                    "com.daemon.lockscreen.brandnew",
                    NotificationManager.IMPORTANCE_HIGH
                ).apply {
                    enableLights(false)
                    setShowBadge(false)
                    enableVibration(false)
                    setSound(null, null)
                }
                NotificationManagerCompat.from(context)
                    .createNotificationChannel(notificationChannel)
                return notificationChannel.id
            }
        }
        DaemonKeepAlive.startWork()
    }

    override fun onCreate() {
        super.onCreate()
        if (!isMainProcess()) {
            return
        }
        registerReceiver(SystemBroadcastReceiver(), IntentFilter().apply {
            addAction(Intent.ACTION_PACKAGE_REMOVED)
            addAction(Intent.ACTION_PACKAGE_ADDED)
            addAction(Intent.ACTION_PACKAGE_CHANGED)
            addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
            addDataScheme("package")
        })
    }
}